package com.lzxuni.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author:孙志强
 * @create:2019-01-22 10:19
 * @Modified BY:
 **/
@ConfigurationProperties(prefix = "spring.mail")
@Component
public class MailConfig {
	@Autowired
	private JavaMailSenderImpl javaMailSender;
	private Boolean open;
	private String sendto;

	public Boolean getOpen() {
		return open;
	}

	public void setOpen(Boolean open) {
		this.open = open;
	}

	public String getSendto() {
		return sendto;
	}

	public void setSendto(String sendto) {
		this.sendto = sendto;
	}


	public void sendMail(String subject, String text, File file) {
		try {
			MimeMessage mimeMessage = javaMailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
			helper.setSubject(subject);
			helper.setText(text,true);
			helper.setTo(getSendto());
			helper.setFrom(javaMailSender.getUsername());
			if (file != null) {
				helper.addAttachment(file.getName()==null ? file.getName() : "", file);
			}
			if(getOpen()){
				javaMailSender.send(mimeMessage);
			}
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	public void sendMail(String subject, String text) {
		sendMail(subject,text,null);
	}
}
